from django import forms
from django.core.exceptions import ValidationError

from web import models
from web.forms.bootstrap import BootStrapForm


class FolderModelForm(BootStrapForm, forms.ModelForm):

    class Meta:
        model = models.FileRepository
        fields = ['name']

    def __init__(self, request, parent_obj, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        self.parent_obj = parent_obj

    def clean_name(self):
        name = self.cleaned_data.get('name')

        # 数据库判断当前目录下此文件夹是否已存在

        # 说明当前在根目录
        file_queryset = models.FileRepository.objects.filter(file_type=2, name=name, project=self.request.tracer.project)

        # 当前目录是有父目录的（如果父目录一致，并且当前文件夹名字一致）
        if self.parent_obj:
            file_obj = file_queryset.filter(parent=self.parent_obj).first()
        # 当前目录在根目录
        else:
            file_obj = file_queryset.filter(parent__isnull=True).first()
        if file_obj:
            raise ValidationError('文件夹已存在')
        return name

